package com.zmc.admin.controller.system;


import com.zmc.admin.application.UserApplicationService;
import com.zmc.admin.infrastructure.bean.vo.user.SysUserVo;
import com.zmc.admin.infrastructure.entity.SysPostEntity;
import com.zmc.admin.infrastructure.entity.SysRoleEntity;
import com.zmc.admin.infrastructure.entity.SysUserEntity;
import com.zmc.admin.infrastructure.bean.query.SysUserQuery;
import com.zmc.admin.infrastructure.service.SysDeptService;
import com.zmc.admin.infrastructure.service.SysPostService;
import com.zmc.admin.infrastructure.service.SysRoleService;
import com.zmc.admin.infrastructure.service.SysUserService;
import com.zmc.common.annotation.PreventRepeatSubmit;
import com.zmc.common.enums.RequestSourceEnum;
import com.zmc.common.response.AjaxResult;
import com.zmc.common.utils.MD5Utils;
import com.zmc.common.utils.PageUtils;
import com.zmc.common.utils.R;
import com.zmc.common.utils.StringUtils;
import com.zmc.common.utils.poi.ExcelUtil;
import com.zmc.common.utils.token.AuthTokenService;
import com.zmc.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息
 * @author zmc
 */
@RestController
@RequestMapping("/user")
public class SysUserController {
    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysDeptService deptService;

    @Autowired
    private SysPostService postService;

    @Autowired
    private AuthTokenService authTokenService;

    @Autowired
    private UserApplicationService userApplicationService;

    /**
     * 获取用户列表
     */
    @PostMapping("/list")
    public R list(@RequestBody SysUserQuery query) {
        PageUtils page = userService.pageUserList(query);
        return R.page(page);
    }

    @PostMapping("/export")
    @PreventRepeatSubmit(lockByPerson = true, source = RequestSourceEnum.MANAGE)
    public void export(HttpServletResponse response, SysUserQuery query) {
        List<SysUserEntity> list = userService.selectUserList(query);
        ExcelUtil<SysUserEntity> util = new ExcelUtil<>(SysUserEntity.class);
        util.exportExcel(response, list, "用户数据");
    }

    @PostMapping("/importData")
    public R importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUserEntity> util = new ExcelUtil<>(SysUserEntity.class);
        List<SysUserEntity> userList = util.importExcel(file.getInputStream());
        String operName = authTokenService.getUserInfo().getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return R.ok(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUserEntity> util = new ExcelUtil<>(SysUserEntity.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PostMapping("/detail")
    public R getInfo(@RequestBody SysUserVo vo) {
        Long userId = vo.getUserId();
        Map<String, Object> map = new HashMap<>();
        List<SysRoleEntity> roles = roleService.list();
        map.put("roles", roles);
        List<SysPostEntity> posts = postService.list();
        map.put("posts", posts);
        if (StringUtils.isNotNull(userId)) {
            SysUserEntity sysUser = userService.getById(userId);
            map.put(AjaxResult.DATA_TAG, sysUser);
            map.put("postIds", postService.selectPostListByUserId(userId));
            map.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return R.ok(map);
    }

    /**
     * 新增用户
     */
    @PostMapping("/add")
    public R add(@RequestBody SysUserEntity user) {
        userApplicationService.saveUser(user);
        return R.ok();
    }

    /**
     * 修改用户
     */
    @PostMapping("/update")
    public R edit(@RequestBody SysUserEntity user) {
        userApplicationService.updateUser(user);
        return R.ok();
    }

    /**
     * 删除用户
     */
    @PostMapping("/delete")
    public R remove(@RequestBody SysUserVo vo) {
        userApplicationService.removeUser(vo.getUserId());
        return R.ok();
    }

    /**
     * 重置密码
     */
    @PostMapping("/resetPwd")
    @PreventRepeatSubmit(lockByPerson = true, source = RequestSourceEnum.MANAGE)
    public R resetPwd(@RequestBody SysUserEntity user) {
        String salt = IdUtils.fastUUID().substring(0, 16);
        user.setPassword(MD5Utils.encrypt(user.getPassword(), salt));
        user.setSalt(salt);
        user.setUpdateBy(authTokenService.getUserInfo().getUsername());
        userService.updateById(user);
        return R.ok();
    }

    /**
     * 状态修改
     */
    @PostMapping("/changeStatus")
    @PreventRepeatSubmit(lockByPerson = true, source = RequestSourceEnum.MANAGE)
    public R changeStatus(@RequestBody SysUserEntity user) {
        user.setUpdateBy(authTokenService.getUserInfo().getUsername());
        userService.updateById(user);
        return R.ok();
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PostMapping("/authRole/info")
    public R authRole(@RequestBody SysUserVo vo) {
        Long userId = vo.getUserId();
        Map<String, Object> map = new HashMap<>();
        SysUserEntity user = userService.getById(userId);
        List<SysRoleEntity> roles = roleService.selectRolesByUserId(userId);
        map.put("user", user);
        map.put("roles", roles);
        return R.ok(map);
    }

    @PostMapping("/info")
    public R info() {
        return R.ok(userService.getById(authTokenService.getUserInfo().getUserId()));
    }

    /**
     * 获取部门树列表
     */
    @PostMapping("/deptTree")
    public R deptTree() {
        return R.ok(deptService.selectDeptTreeList());
    }
}
